package com.cac.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Value("${toolTask.corePoolSize}")
    int corePoolSize;
    @Value("${toolTask.maxPoolSize}")
    int maxPoolSize;
    @Value("${toolTask.queueCapacity}")
    int queueCapacity;
    @Value("${toolTask.keepAliveSeconds}")
    int keepAliveSeconds;
    /***
     * 设置  @Async 注解线程池配置
     * **/
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//核心线程数
        executor.setMaxPoolSize(maxPoolSize);//最大线程数量
        executor.setQueueCapacity(queueCapacity);//队列大小
        executor.setKeepAliveSeconds(keepAliveSeconds);//线程最大空闲时间
        executor.setThreadNamePrefix("async-Executor-");//新创建线程名称前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
